package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.InterviewDTO;
import com.lastproject.dto.QuestionDTO;
import com.lastproject.ejb.entities.Interview;
import com.lastproject.ejb.entities.Question;
import com.lastproject.ejb.service.MailSender;
import com.lastproject.ejb.util.InterviewConversion;

/**
 * Session Bean implementation class InterviewDAO
 * 
 * Hodgyai Zoltan
 */
@Stateless
public class InterviewDAO implements InterviewDAORemote {

	@PersistenceContext (unitName = "LastProjectEJB")
	EntityManager em;

	@EJB
	InterviewConversion conv;

	/**
	 * Default constructor.
	 */
	public InterviewDAO() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void create(InterviewDTO interviewDTO) {
		
		em.persist(conv.fromDTO(interviewDTO));
	}

	@Override
	public void edit(InterviewDTO interviewDTO) {
		// TODO Auto-generated method stub
		em.merge(conv.fromDTO(interviewDTO));
	}

	@Override
	public void remove(InterviewDTO interviewDTO) {
		// TODO Auto-generated method stub
		em.remove(em.merge(conv.fromDTO(interviewDTO)));
	}

	@Override
	public InterviewDTO findById(int id) {
		// TODO Auto-generated method stub
		Interview interview = new Interview();

		interview = em.find(Interview.class, id);

		return conv.fromEntity(interview);
	}

	@Override
	public List<InterviewDTO> getAll() {
		// TODO Auto-generated method stub
		List<Interview> iList = new ArrayList<Interview>();

		iList = em.createNamedQuery("Interview.findAll", Interview.class)
				.getResultList();

		List<InterviewDTO> iDTOList = new ArrayList<InterviewDTO>();

		for (Interview i : iList) {
			iDTOList.add(conv.fromEntity(i));
		}

		return iDTOList;
	}

	@Override
	public void sendEmailToCandidate(String sender, String receiver,
			String subject, String content) {
		MailSender mailSender = new MailSender();
		mailSender.sendMail(sender, receiver, subject, content);
		
	}

	@Override
	public List<InterviewDTO> getListOfInterviewsByCandidate(int id) {
		List<Interview> interviews = em.createQuery("SELECT i FROM Interview i WHERE i.candidate.id =:id",
				Interview.class).setParameter("id", id).getResultList();
		List<InterviewDTO> interviewsListByCandidateId = new ArrayList<InterviewDTO>();

		for (Interview interview : interviews) {
			InterviewDTO i = new InterviewDTO();
			i = conv.fromEntity(interview);
			interviewsListByCandidateId.add(i);

		}

		return interviewsListByCandidateId;
	}

	
	

	
	
}
